package com.jiancong.filter;

import com.jiancong.service.impl.SensitiveWordLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;

@Component
class SensitiveWordFileWatcher {

    @Autowired
    private SensitiveWordLoader sensitiveWordLoader;

    /**
     * 初始化文件监听器
     */   
    @Value("${sensitive-word.file-path}")
     private String sensitiveWordFilePath;
    @PostConstruct
    public void watchFile() throws IOException, InterruptedException {
     
        try {
            // 使用 ClassPathResource 获取资源文件
            ClassPathResource resource = new ClassPathResource(sensitiveWordFilePath);
            File file = resource.getFile();
            Path path = file.toPath();
            
            // 创建 WatchService
            WatchService watchService = FileSystems.getDefault().newWatchService();
            path.getParent().register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);

            // 启动监听线程
            new Thread(() -> {
                while (true) {
                    try {
                        WatchKey key = watchService.take();
                        for (WatchEvent<?> event : key.pollEvents()) {
                            // 检查是否是目标文件
                            if (event.context().toString().equals("sensitive_words.txt")) {
                                System.out.println("检测到敏感词文件变化，重新加载...");
                                sensitiveWordLoader.reloadSensitiveWords();
                            }
                        }
                        key.reset();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, "sensitive-word-watcher").start();
            
            System.out.println("敏感词文件监听器已启动，监听路径：" + path);
        } catch (Exception e) {
            System.err.println("启动敏感词文件监听器失败：" + e.getMessage());
            // 记录错误但不中断应用启动
            e.printStackTrace();
        }
    }
}